package org.xinghai.sql.main.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.sf.jsqlparser.JSQLParserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.xinghai.sql.common.api.Result;
import org.xinghai.sql.main.generator.domain.DatabaseTables;
import org.xinghai.sql.main.generator.domain.TableColumns;
import org.xinghai.sql.main.generator.domain.TableRelationships;
import org.xinghai.sql.main.generator.service.DatabaseTablesService;
import org.xinghai.sql.main.generator.service.TableColumnsService;
import org.xinghai.sql.main.generator.service.TableRelationshipsService;
import org.xinghai.sql.main.utils.EntityParserToSqlUtil;
import org.xinghai.sql.main.utils.SqlToEntityParserUtil;

import java.util.List;

/**
 * SQL 解析器，将sql语句解析成Java实体类
 * @author lijia
 * &#064;date  2025/07/28
 */
@RestController
@RequestMapping("/database/sql")
public class SqlController {
    @Autowired
    private DatabaseTablesService databaseTablesService;
    @Autowired
    private TableColumnsService tableColumnsService;
    @Autowired
    private TableRelationshipsService tableRelationshipsService;
    @PostMapping("/parseCreateTableName")
    // 解析SQL语句，返回表信息表
    public Result<?> parseCreateTableName(
            @RequestParam("sql") String sql,
            @RequestParam("databaseName") String databaseName
    )  {
        //持久化储存表
        List<DatabaseTables> databaseTables = SqlToEntityParserUtil.parseCreateTable(sql, databaseName);
        databaseTablesService.saveBatch(databaseTables);
        return Result.success();
    }
    @PostMapping("/parseGetColumnsList")
    // 解析SQL语句，返回列表
    public Result<?> parseGetColumnsList(
            @RequestParam("sql") String sql,
            @RequestParam("databaseName") String databaseName)  {
        //实体化sql语句（列）
        List<TableColumns> tableColumns = SqlToEntityParserUtil. parseCreateTableGetColumns(sql);
        //通过表名查询表id
        int n = 1;
        for (TableColumns tableColumn : tableColumns) {
            Integer tableId = databaseTablesService.
                    getTableIdByTableNameFromDatabaseName(tableColumn.getTableName(), databaseName);
            tableColumn.setTableId(tableId);
            tableColumn.setColumnPosition(n);
            n++;
            //判断是否为外键，添加目标表id，目标列id暂时用不到，所以没写
            if(tableColumn.getForeignTableName()!=null && tableColumn.getIsForeignKey() == 1){
                //通过外键目标表名查询外键目标表id
                Integer foreignTableId = databaseTablesService.getTableIdByTableNameFromDatabaseName(tableColumn.getForeignTableName(), databaseName);
                tableColumn.setForeignTableId(foreignTableId);
                //在目标表中查询外键目标列id通过表id和表名
                Integer foreignColumnId = tableColumnsService.
                        getColumnIdByColumnNameAndForeignTableId(foreignTableId,tableColumn.getForeignColumnName());
                tableColumn.setForeignColumnId(foreignColumnId);
            }
        }
        tableColumnsService.saveBatch(tableColumns);
        return Result.success();
    }
    @PostMapping("/parseTableTableList")


    //解析SQL语句，返回表信息的关系列表
    public Result<List<TableRelationships>> parseSqlTableList(
            @RequestParam("sql") String sql) throws JSQLParserException {
        //持久化储存关系
        List<TableRelationships> tableRelationships = SqlToEntityParserUtil.parseTableRelationships(sql);
        System.out.println("++++++++++++"+tableRelationships);
        //通过sourceTable名字查询sourceTableID
        for (TableRelationships tableRelationship : tableRelationships) {
          Integer   sourceTableID = databaseTablesService.getTableIdByTableName(tableRelationship.getSourceTable());
            tableRelationship.setSourceTableID(Long.valueOf(sourceTableID));
            //通过targetTable名字查询targetTableID
            Integer targetTableID = databaseTablesService.getTableIdByTableName(tableRelationship.getTargetTable());
            tableRelationship.setTargetTableID(Long.valueOf(targetTableID));
        }
        tableRelationshipsService.saveBatch(tableRelationships);
        return Result.success(tableRelationships);
    }



    //生成sql语句,通过所属数据库查询
    @GetMapping("/generateSql")
    public Result<String> generateSql(
           @RequestParam("databaseName") String databaseName
    ){
        //通过所属数据库查表
        List<DatabaseTables> databaseTables = databaseTablesService.list(
                new LambdaQueryWrapper<DatabaseTables>().
                        eq(DatabaseTables::getDatabaseName, databaseName));
        //通过表id查询列
        List<TableColumns> tableColumns = tableColumnsService.getList(databaseTables);
        String sql = EntityParserToSqlUtil.generateFullSql(databaseTables, tableColumns);
        return Result.success(sql);
    }

}
